package com.mindtree.vi.business.javaservice;

import java.io.IOException;

import javassist.CannotCompileException;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtConstructor;
import javassist.CtField;
import javassist.CtMethod;
import javassist.CtNewConstructor;
import javassist.CtNewMethod;
import javassist.NotFoundException;

import org.springframework.beans.factory.annotation.Required;

import com.mindtree.vi.dbaccess.datatypes.problem.Problem;
import com.mindtree.vi.dbaccess.manager.problem.ProblemTableManager;

public class MainMethodInjector {

	private ProblemTableManager problemTableManager;

	@Required
	public void setProblemTableManager(ProblemTableManager problemTableManager) {
		this.problemTableManager = problemTableManager;
	}

	public CtClass injectMainMethod() {
		System.out.println("in the injection of the main method");
		boolean exception = false;
		ClassPool pool = ClassPool.getDefault();
		CtClass cc = null;
		Problem problem = problemTableManager.find(1);
		try {
			String className = problem.getProblemDescription().getClassName();
			String methodName = problem.getProblemDescription().getMethodName();
			String returnType = problem.getProblemDescription()
					.getMethodReturnType();
			String params = problem.getProblemDescription()
					.getMethodArguments();
			cc = pool.get(className);
			CtField field = new CtField(CtClass.longType, "age", cc);
			CtConstructor constructor = CtNewConstructor.make("public "
					+ className + "(int message){" + "" + "}", cc);
			cc.addConstructor(constructor);
			CtMethod method = CtNewMethod.make(
					"public static void main(String[] args){" + "}", cc);
			method.insertBefore("new " + className + "(1)");
			cc.addField(field);
			cc.addMethod(method);
			cc.writeFile();
		} catch (NotFoundException e) {
			exception = true;
		} catch (CannotCompileException e) {

		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (exception) {

			} else {

			}
		}
		return cc;

	}
}
